// map.js
// Mon 15 Mar 2010 10:23:00 AM EET

/* 
Initialization and simple manipulation functions for GeoTree demo.

Copyright (c) 2010 Artem Dudarev
License: Apache 2.0
*/

var map;
var points_data = [];
var markersArray = [];
var pointsArray = [];
var citiesArray = [];
var tempMarkersArray = [];

// Deletes all markers in the array by removing references to them
// http://code.google.com/apis/maps/documentation/v3/overlays.html
function deleteArray(a) {
    if (a) {
        for (i in a) {
            a[i].setMap(null);
        }
        a.length = 0;
    }
}

function deleteOverlays() {
    deleteArray(citiesArray);
    deleteArray(pointsArray);
    deleteArray(tempMarkersArray);
}

// Initialization function
function initialize_map() {
    var myOptions = {
        zoom: 4,
        center: new google.maps.LatLng(48.03,20),
        mapTypeControl: true,
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
        navigationControl: true,
        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    // Insert this overlay map type as the first overlay map type at
    // position 0. Note that all overlay map types appear on top of
    // their parent base map.
    map.overlayMapTypes.insertAt(
        0, new CoordMapType(new google.maps.Size(256, 256)));

    google.maps.event.addListener(map, 'zoom_changed', function() {
        setTimeout(load_points, 200);
    });

    google.maps.event.addListener(map, 'click', function(event) {
        addMarker(event.latLng);
    });

    load_points();
}

// Add a marker and trigger recalculation of the path and elevation
function addMarker(latlng) {
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        draggable: false,
        icon: "http://maps.google.com/mapfiles/marker_green.png"
    })
    tempMarkersArray.push(marker);
    var z = map.getZoom();
    $.post("/insert_point", {
        lat: latlng.lat(),
        lng: latlng.lng(),
        z: z,
        importance: 1
        },
        function (data) { 
            $('#geo_tree_info').html(data);
        }
    );

}

function get_geotree(geotree_name){

    z = map.getZoom();
    centerTile = PointToTile(map.getCenter(),z);
    center =  centerTile.x + ',' + centerTile.y + ',' + z;
    
    url = '/t/?c=' + center + '&gt=' + geotree_name;
    
    if (geotree_name == 'points'){
        var icon = "http://maps.google.com/mapfiles/marker_green.png";
    } else {
        var icon = "http://maps.google.com/mapfiles/marker.png";
    }

    $.ajax({ url: url, success: function(data){
            points_data = eval(data);
            for(var i=0; i<points_data.length; i++){
                var lat = points_data[i]['coord'][0];
                var lon = points_data[i]['coord'][1];
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat,lon), 
                    map: map,
                    icon: icon,
                    importance: points_data[i]['importance'],
                    name: points_data[i]['name'],
                    info: lat
                });   
                if (geotree_name == 'points'){
                    pointsArray.push(marker);
                } else {
                    citiesArray.push(marker);
                }
                attachInfoDiv(marker,i);
                $('#marker_info').html('');
            }
      }});
}

// Load JSON of all points in tiles (3x3 tiles around center tile)
function load_points(){
    deleteOverlays();
    if ($('#cities_checkbox').attr('checked')) {
        get_geotree('cities');
    }
    if ($('#points_checkbox').attr('checked')) {
        get_geotree('points');
    }

}

// Update city info div when mouseover over marker
function attachInfoDiv(marker,i){
    // http://stackoverflow.com/questions/829353/google-maps-trouble-closures-passing-by-reference
    var f = function(marker, map)
    {
        return function()
        {
            var html = '<h2>'+marker.name+'</h2>';
            html += 'importance: '+marker.importance+'<br/>';
            $('#marker_info').html(html);
        }
    }
    google.maps.event.addListener(marker, "mouseover", f(marker, map));

}
